package io.api.modules.project.controller;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.ImmutableBiMap;
import io.admin.common.constant.Constant;
import io.admin.common.exception.ErrorCode;
import io.admin.common.page.PageData;
import io.admin.common.utils.Result;
import io.admin.common.validator.ValidatorUtils;
import io.api.annotation.LoginUser;
import io.api.enums.UserRole;
import io.api.modules.login.entity.UserEntity;
import io.api.modules.project.dto.AnchorDTO;
import io.api.modules.project.dto.PageAnchorDTO;
import io.api.modules.project.dto.LineDTO;
import io.api.modules.project.dto.UserLineDTO;
import io.api.modules.project.service.AnchorService;
import io.api.modules.project.service.LineService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 项目线路关系表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2024-07-12
 */
@RestController
@RequestMapping("/api/line")
@Api(tags="项目线路关系表")
public class LineController {
    @Autowired
    private LineService lineService;
    @Autowired
    private AnchorService anchorService;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    public Result page(@ApiIgnore @RequestParam Map<String, Object> params, @LoginUser UserEntity user){
        if (Objects.nonNull(params.get("projectId"))) {
            String projectIdStr = (String) params.get("projectId");
            Long projectId = Long.parseLong(projectIdStr);
            params.put("projectId", projectId);
        } else {
            return new Result<>().error("项目ID不能为空");
        }
        PageData<LineDTO> page = lineService.page(params);

        List<LineDTO> list = page.getList().stream().map(i -> {
            List<AnchorDTO> anchorDTOS = anchorService.list(ImmutableBiMap.of("lineId", i.getId()));
            i.setAnchors(anchorDTOS);
            return i;
        }).collect(Collectors.toList());
        page.setList(list);

        return new Result<PageData<LineDTO>>().ok(page);
    }

    @GetMapping("/user/page")
    public Result userPage(@ApiIgnore @RequestParam Map<String, Object> params, @LoginUser UserEntity user){
        if (user.getUserrole() != UserRole.MANAGER.getValue()) {
            params.put("userId", user.getId());
        }
        PageData<UserLineDTO> page = lineService.pageLine(params);
        return new Result<PageData<UserLineDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    public Result<LineDTO> get(@PathVariable("id") Long id){
        LineDTO data = lineService.get(id);
        List<AnchorDTO> anchorDTOS = anchorService.list(data.getId());
        data.setAnchors(anchorDTOS);
        return new Result<LineDTO>().ok(data);
    }
    @GetMapping("list")
    public Result<List<LineDTO>> list(@ApiIgnore @RequestParam Map<String, Object> params, @LoginUser UserEntity user){
        if (user.getUserrole() != UserRole.MANAGER.getValue()) {
            params.put("userId", user.getId());
        }
        String idsStr = (String) params.get("ids");
        if (StrUtil.isNotBlank(idsStr)) {
            String[] ids = idsStr.split(",");
            params.put("ids", ids);
        }
        List<LineDTO> list = lineService.selectList(params);
        list.stream().map(i -> {
            List<AnchorDTO> pageAnchorDTOS = anchorService.list(i.getId());
            i.setAnchors(pageAnchorDTOS);
            return i;
        }).collect(Collectors.toList());
        return new Result<List<LineDTO>>().ok(list);
    }

    @PostMapping
    @ApiOperation("保存")
    public Result save(@RequestBody LineDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto);
        if (lineService.countByNameAndProjectId(dto.getName(), dto.getProjectId(), null) > 0) {
            return new Result().error(ErrorCode.DB_RECORD_EXISTS);
        }
        lineService.save(dto);
        return new Result().ok(ImmutableBiMap.of("id", dto.getId()));
    }

    @PutMapping
    @ApiOperation("修改")
    public Result update(@RequestBody LineDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto);
        if (lineService.countByNameAndProjectId(dto.getName(), dto.getProjectId(), dto.getId()) > 0) {
            return new Result().error(ErrorCode.DB_RECORD_EXISTS);
        }
        lineService.update(dto);

        return new Result();
    }

    @DeleteMapping("{id}")
    @ApiOperation("删除")
    public Result delete(@PathVariable("id") Long id){
        if (anchorService.countByLineId(id) > 0) {
            return new Result().error(ErrorCode.NOT_NULL, "该线路下有设备，请先删除设备");
        }
        lineService.deleteById(id);
        return new Result();
    }

    @GetMapping("exist")
    public Result exist(
            @RequestParam(value = "name") String name,
            @RequestParam(value = "projectId") Long projectId,
            @RequestParam(value = "lineId", required = false) Long lineId
    ){
        if (lineService.countByNameAndProjectId(name, projectId, lineId) > 0) {
            return new Result().error("线路名称已存在");
        } else {
            return new Result().ok("线路不存在");
        }
    }



}